package com.example.petcare.service.serviceImpl;

import com.example.petcare.exception.NoValueException;
import com.example.petcare.mapper.BuyMapper;
import com.example.petcare.mapper.HostMapper;
import com.example.petcare.pojo.Goods;
import com.example.petcare.pojo.HostDemand;
import com.example.petcare.service.BuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class BuyServiceImpl implements BuyService {

    @Autowired
    private BuyMapper buyMapper;

    @Autowired
    private HostMapper hostMapper;


    // 查看增值商品列表
    @Override
    public List<Goods> getGoodsList(Integer hostId) {



        // 先根据hostId查询托管需求
        HostDemand hostDemand = hostMapper.findById(hostId);

        // 然后获取到providerId
        Integer providerId = hostDemand.getProviderId();

        // 如果已经完成托管需求,则不能购买增值商品
        if (hostDemand.isOrderStatus()) {
            throw new RuntimeException("托管需求已完成,不能购买增值商品");
        }

        // 根据providerId查询增值商品
        List<Goods> goodsList = hostMapper.getGoodsList(providerId);

        return goodsList;


    }

    // 购买增值商品，讲将增值商品添加到购物车
    @Override
    public void addGoodsToCart(Integer gId, Integer hostId) {

        // 先在购物车里查询是否已经存在该商品
        Integer count = buyMapper.checkGoodsInCart(gId, hostId);

        // 如果已经存在该商品,则抛出异常
        if (count > 0) {
            throw new NoValueException("你已经购买过该增值商品,不能重复购买");
        }


        // 将增值商品添加到购物车
        buyMapper.addGoodsToCart(gId, hostId);
    }

    // 查询自己买了什么增值服务
    @Override
    public List<Goods> getGoodsInCart(Integer hostId) {

        // 查询购物车里的增值商品
        List<Goods> goodsList = buyMapper.getGoodsInCart(hostId);

        // 如果购物车里没有增值商品,则抛出异常
        if (goodsList.size() == 0) {
            throw new NoValueException("你没有购买增值商品");
        }

        return goodsList;
    }

    // 查询购物车中指定的gId是否存在
    @Override
    public Integer checkGoodsInCart(Integer gId, Integer hostId) {

        // 查询购物车中指定的gId是否存在
        Integer count = buyMapper.checkGoodsInCart(gId, hostId);

        return count;
    }


}
